import React, { useEffect, useMemo, useState } from 'react';
import { ISheetItem } from '@/pages/Analysis/type';
import { ITreeNode } from '@/pages/data';
import { Modal, Table, Tree } from 'antd';
import styles from './index.less';
import { executesql } from '@/services/analysis';
import { IResponse } from '@/models/connect';
import { getTextWidth } from '@/utils/utils';

interface IProps {
  views: ISheetItem[]
  visible: boolean
  onCanel: () => void
  onSave: (viewId: number) => void
}

let uniqueId = 0;

function generateUniqueId() {
  // eslint-disable-next-line no-plusplus
  return `table-f2-${uniqueId++}`;
}

const ViewSelect: React.FC<IProps> = (props) => {
  const tableId: string = generateUniqueId();
  const { views, visible, onCanel, onSave } = props;
  const [viewTrees, setViewTrees] = useState<any[]>();
  const [expandedKeys, setExpandedKeys] = useState<Array<string>>([]); // 展开指定的树节点
  const [selectSheet, setSelectSheet] = useState<ISheetItem>(); // 选中展示的数据表
  const [tableDatas, setTableDatas] = useState<any[]>(); // 选中展示的数据表

  /**
   * 监听接口返回的对象数据并初始化数据
   */
  useEffect(() => {
    if (views && views.length) {
      // 初始化文件夹树形结构
      const folders: ITreeNode[] = views.map(d => ({
        key: d.id,
        value: d.id,
        title: d.name,
        parent: d.parentId,
        isFolder: d.isFolder,
      }));
      const searchFoldersById = (datas: ITreeNode[], pId: any) => {
        const children = datas.filter(v => v.parent === pId);
        if (children) {
          children.map(v => {
            const children1 = searchFoldersById(datas, v.key);
            v.children = children1;
            return v;
          });
        }
        return children;
      };
      const folderTrees = folders.filter((tree: any) => !tree.parent || tree.parent === '').map((root) => {
        root.children = searchFoldersById(folders, root.key);
        return root;
      });
      setViewTrees(folderTrees);
    }
  }, [views]);
  useEffect(() => {
    if (selectSheet) {
      executesql({
        limit: 20,
        sourceId: selectSheet.sourceId,
        sql: selectSheet.sql,
      }).then(
        (res: IResponse) => {
          if (res.header.code === 200) {
            setTableDatas(res.payload.resultList);
          }
        },
      );
    }
  }, [selectSheet]);
  const columns = useMemo(() => {
    let list: any[] = [];
    if (!selectSheet) {
      return list;
    }
    const model = JSON.parse(selectSheet.model);

    list = Object.keys(model).map((v) => {
      let maxLen: number = getTextWidth(v);
      tableDatas && tableDatas.forEach((d: any) => {
        const textWidth: number = getTextWidth(d[v]);
        if (textWidth > maxLen) {
          maxLen = textWidth;
        }
      });
      return {
        title: v,
        dataIndex: v,
        key: v,
        width: maxLen + 25,
      };
    });
    return list;
  }, [tableDatas]);
  const onSelect = (selectedKeys: any, info: any) => {
    setExpandedKeys(selectedKeys);
    if (!info.node.isFolder) {
      setSelectSheet(views.find(v => v.id === selectedKeys[0]));
    }
  };
  return (
    <Modal
      title='选择视图'
      centered
      visible={visible}
      onOk={() => {
        selectSheet && onSave(selectSheet.id) && onCanel();
      }}
      onCancel={() => onCanel()}
      width='1000px'
    >
      <div className={styles.contain}>
        <div className={styles.left}>
          <Tree
            treeData={viewTrees}
            onSelect={onSelect}
            expandedKeys={expandedKeys}
            blockNode
          />
        </div>
        <div className={styles.right}>
          <Table
            id={tableId}
            columns={columns}
            dataSource={tableDatas}
            size='small'
            scroll={{ y: 339 }}
            pagination={false}
          />
        </div>
      </div>
    </Modal>

  );
};

export default ViewSelect;
